Page({
  data: {
    houseList: [],
    loading: false,
    residentId: '',
    token: ''
  },

  onLoad() {
    // 获取全局变量
    const app = getApp();
    console.log('房屋收藏页面 - 全局变量信息:', {
      residentId: app.globalData.residentId,
      token: app.globalData.token,
      baseUrl: app.globalData.baseUrl
    });
    
    this.setData({
      residentId: app.globalData.residentId,
      token: app.globalData.token
    });
    
    // 延迟加载房屋收藏，确保residentId已设置
    setTimeout(() => {
      this.loadHouseCollection();
    }, 500);
  },

  onShow() {
    // 页面显示时刷新数据
    const app = getApp();
    console.log('onShow - 重新获取residentId:', app.globalData.residentId);
    
    this.setData({
      residentId: app.globalData.residentId,
      token: app.globalData.token
    });
    
    this.loadHouseCollection();
  },

  // 加载房屋收藏
  loadHouseCollection() {
    console.log('开始加载房屋收藏...');
    console.log('检查条件:', {
      residentId: this.data.residentId,
      token: this.data.token ? '有token' : '无token'
    });

    if (!this.data.residentId) {
      console.log('缺少residentId');
      wx.showToast({
        title: '缺少住户信息，请重新登录',
        icon: 'none',
        duration: 3000
      });
      return;
    }

    if (!this.data.token) {
      console.log('缺少token');
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 3000
      });
      return;
    }

    console.log('当前住户ID:', this.data.residentId);
    console.log('当前Token:', this.data.token);

    this.setData({ loading: true });

    const app = getApp();
    const baseUrl = app.globalData.baseUrl;

    console.log('请求URL:', `${baseUrl}/house/house/collectionByResident/${this.data.residentId}`);
    console.log('请求参数:', { residentId: this.data.residentId });

    wx.request({
      url: `${baseUrl}/house/house/collectionByResident/${this.data.residentId}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + this.data.token
      },
      success: (res) => {
        console.log('房屋收藏接口返回:', res.data);
        console.log('返回数据详情:', JSON.stringify(res.data, null, 2));
        
        if (res.data.code === 200) {
          const houseList = res.data.data || [];
          console.log('房屋收藏数量:', houseList.length);
          
          if (houseList.length > 0) {
            // 处理数据，添加格式化字段
            const processedHouseList = houseList.map(item => {
              console.log('处理房屋收藏:', item);
              return {
                ...item,
                formattedArea: this.formatArea(item.buildingArea),
                formattedLayout: this.formatLayout(item.layout),
                formattedFloor: this.formatFloor(item.floorNumber, item.unitNumber)
              };
            });
            
            this.setData({
              houseList: processedHouseList
            });
          } else {
            this.setData({
              houseList: []
            });
            console.log('没有找到房屋收藏');
            wx.showToast({
              title: '暂无房屋收藏',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg || '获取房屋收藏失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取房屋收藏失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 格式化面积
  formatArea(area) {
    if (!area) return '0㎡';
    return `${area}㎡`;
  },

  // 格式化户型
  formatLayout(layout) {
    if (!layout) return '户型未知';
    return layout;
  },

  // 格式化楼层和单元
  formatFloor(floorNumber, unitNumber) {
    let result = '';
    if (floorNumber) {
      result += `${floorNumber}层`;
    }
    if (unitNumber) {
      result += `${unitNumber}单元`;
    }
    return result || '楼层未知';
  },

  // 跳转到房屋详情页
  goToHouseDetail(e) {
    const houseId = e.currentTarget.dataset.id;
    console.log('跳转到房屋详情页，房屋ID:', houseId);
    
    wx.navigateTo({
      url: `/service/pages/leaseHouseDetail/leaseHouseDetail?id=${houseId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadHouseCollection();
    wx.stopPullDownRefresh();
  }
})